package com.globant.ErrorManager;

import java.io.File;
import java.io.IOException;

import com.globant.AutomateEMR.AutomateBigDataFunctions;
import com.globant.AutomateEMR.FileManager;
import com.globant.AutomateEMR.PropertyLoader;
import com.globant.Exceptions.BigDataFunctionException;
import com.globant.Exceptions.ErrorManagerException;
/**
 * AnswerToError.Class that answer to a report error.
 * 
 * @author leandro.mora
 * @version 20130125v1.1
 */
public class AnswerToError {	

	/* 
	================================================================================================
	 Fields
	================================================================================================
	*/	
	PropertyLoader propLoader;
	public static final String     TEMPLATE_BEEHIVE_FORMAT    = "beehive_autodesk_com";
	public static final String     TEMPLATE_HA_FORMAT         = "haproxy";
	public static final int		   NUMBER_ATTEMPS 		      = 15;

	/* 
	================================================================================================
	 Constructor
	================================================================================================
	*/	
	public AnswerToError(PropertyLoader propLoader) {
			this.propLoader=propLoader;
	}

	
	/* 
	================================================================================================
	 Methods
	================================================================================================
	*/
	/**
	 * answer to an error. Inform that there was and error and wait so the user can make some changes
	 * After that, it deletes the error report and run the big data functions again
	 * @author leandro.mora
	 * @version 20130125v1.1
	 */
	public void answer(String ErrorParam, File reportDirectory) throws ErrorManagerException {		
		try {
			FileManager f=new FileManager();
			System.out.println("Let's delete the failed report Directories");
			this.informAndSleep(ErrorParam,reportDirectory);
			f.deleteFiles(reportDirectory);
			runBigDataScript(reportDirectory.getName());
		}catch(Exception e){
			e.printStackTrace();
			throw new ErrorManagerException("There was an error while managing Errors");
		}
		
	}
	private void informAndSleep(String errorParam, File reportDirectory) throws IOException, InterruptedException {
		String minutesToWait = propLoader.readProperty("MinutesBeforeReprocessing");
		int milis = Integer.parseInt(minutesToWait) * 1000 * 60;
		System.out.println("You have "+minutesToWait+" minutes to revise the application before re-processing");
		Thread.sleep(milis);
	}
	
	/**
	 * runBigDataScript.Based on which report failed, 
	 * runs an specific script to process the log file again, 
	 * and wait till it finish.
	 * 
	 * @author leandro.mora
	 * @version 20130125v1.1
	 */
	public void runBigDataScript(String fileToReProcess) throws IOException, BigDataFunctionException, ErrorManagerException{
		String jobID = "";
		System.out.println("Running Big Data Script..");
		Process p = runBDScript(fileToReProcess);
		AutomateBigDataFunctions autBd=new AutomateBigDataFunctions(propLoader);
		jobID = autBd.extractJobId(p);
		autBd.waitBeforeFinishProcessing(jobID);
	}
	/**
	 * runBigDataScript.Based on which report failed, 
	 * runs an specific script.
	 * 
	 * @author leandro.mora
	 * @version 20130125v1.1
	 */
	private Process runBDScript(String fileToReProcess) throws IOException, ErrorManagerException {
		String pathToS3File = propLoader.readProperty("PathToBucket")+propLoader.readProperty("PathToInputProcessedLogs");
		System.out.println("PATH "+pathToS3File);
		int attemps=0;
		File logFolder=new File(pathToS3File);
		File logFile=this.getLogStored(logFolder);
		while(logFile==null && attemps<NUMBER_ATTEMPS){
			logFile=this.getLogStored(logFolder);
		}
		pathToS3File=propLoader.readProperty("PathToInputProcessedLogs")+logFile.getName();
		
		Process p = Runtime.getRuntime().exec(propLoader.readProperty("PathToScripts") + fileToReProcess+".sh "
												+ pathToS3File + " "+ propLoader.readProperty("AbsPathToElasticMapReduce"));
		return p;
	}
	/**
	 * GetLogStored.Get the log file from a given folder.
	 * 
	 * @author leandro.mora
	 * @version 20130125v1.1
	 */
	public File getLogStored(File logFolder) {
		File resultFile=null;
		FileManager fmanager=new FileManager();
		File[] logs=logFolder.listFiles();
		for(int i=0;i<logs.length;i++){
			if(logs[i].getName().contains(TEMPLATE_BEEHIVE_FORMAT)){
				if(fmanager.validateLog(logs[i])){
					return logs[i];
				}
			}
		}
		return resultFile;
	}

	public static void main(String[] args) throws ErrorManagerException {
		PropertyLoader propLoader=new PropertyLoader(args[0]);
		AnswerToError fstAns2Error=new AnswerToError(propLoader);
		File fWord=new File("/mnt/s3bucket/ProcessedLogs/toDatabase/akn_NoResultQuery_fact");
		fstAns2Error.answer("1", fWord);
	}
	
}
